<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="订单号" prop="orderNo">
        <el-input v-model="formData.orderNo" placeholder="请输入订单号" />
      </el-form-item>
      <el-form-item label="乘客ID" prop="userId">
        <el-input v-model="formData.userId" placeholder="请输入乘客ID" />
      </el-form-item>
      <el-form-item label="城市" prop="city">
        <el-input v-model="formData.city" placeholder="请输入城市" />
      </el-form-item>
      <el-form-item label="车辆类型" prop="vehicleClass">
        <el-select v-model="formData.vehicleClass" placeholder="请选择车辆类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.VEHICLE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态ID" prop="orderStatus">
        <el-select v-model="formData.orderStatus" placeholder="请选择订单状态ID">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.ORDER_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上车地点" prop="pickupLocation">
        <el-input v-model="formData.pickupLocation" placeholder="请输入上车地点" />
      </el-form-item>
      <el-form-item label="下车地点" prop="dropoffLocation">
        <el-input v-model="formData.dropoffLocation" placeholder="请输入下车地点" />
      </el-form-item>
      <el-form-item label="起点名称" prop="start">
        <el-input v-model="formData.start" placeholder="请输入起点名称" />
      </el-form-item>
      <el-form-item label="起点城市" prop="startCity">
        <el-input v-model="formData.startCity" placeholder="请输入起点城市" />
      </el-form-item>
      <el-form-item label="起点详细地址" prop="startAddress">
        <el-input v-model="formData.startAddress" placeholder="请输入起点详细地址" />
      </el-form-item>
      <el-form-item label="起点纬度" prop="startLatitude">
        <el-input v-model="formData.startLatitude" placeholder="请输入起点纬度" />
      </el-form-item>
      <el-form-item label="起点经度" prop="startLongitude">
        <el-input v-model="formData.startLongitude" placeholder="请输入起点经度" />
      </el-form-item>
      <el-form-item label="终点名称" prop="end">
        <el-input v-model="formData.end" placeholder="请输入终点名称" />
      </el-form-item>
      <el-form-item label="终点城市" prop="endCity">
        <el-input v-model="formData.endCity" placeholder="请输入终点城市" />
      </el-form-item>
      <el-form-item label="终点详细地址" prop="endAddress">
        <el-input v-model="formData.endAddress" placeholder="请输入终点详细地址" />
      </el-form-item>
      <el-form-item label="终点纬度" prop="endLatitude">
        <el-input v-model="formData.endLatitude" placeholder="请输入终点纬度" />
      </el-form-item>
      <el-form-item label="终点经度" prop="endLongitude">
        <el-input v-model="formData.endLongitude" placeholder="请输入终点经度" />
      </el-form-item>
      <el-form-item label="订单金额(元)" prop="orderAmount">
        <el-input v-model="formData.orderAmount" placeholder="请输入订单金额(元)" />
      </el-form-item>
      <el-form-item label="服务时长(分钟)" prop="serviceDuration">
        <el-input v-model="formData.serviceDuration" placeholder="请输入服务时长(分钟)" />
      </el-form-item>
      <el-form-item label="服务里程(公里)" prop="serviceDistance">
        <el-input v-model="formData.serviceDistance" placeholder="请输入服务里程(公里)" />
      </el-form-item>
      <el-form-item label="下单来源" prop="fromId">
        <el-select v-model="formData.fromId" placeholder="请选择下单来源">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.ORDER_FROM)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付类型" prop="payId">
        <el-select v-model="formData.payId" placeholder="请选择支付类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.PAY_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="联系手机号" prop="mobile">
        <el-input v-model="formData.mobile" placeholder="请输入联系手机号" />
      </el-form-item>
      <el-form-item label="预约时间" prop="appointmentTime">
        <el-date-picker
          v-model="formData.appointmentTime"
          type="date"
          value-format="x"
          placeholder="选择预约时间"
        />
      </el-form-item>
      <el-form-item label="状态文本" prop="statusText">
        <el-input v-model="formData.statusText" placeholder="请输入状态文本" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
      <el-form-item label="司机ID" prop="driverId">
        <el-input v-model="formData.driverId" placeholder="请输入司机ID" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { OrderApi, Order } from '@/api/ride/orders'

/** 订单管理 表单 */
defineOptions({ name: 'OrderForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  orderId: undefined,
  orderNo: undefined,
  userId: undefined,
  city: undefined,
  vehicleClass: undefined,
  orderStatus: undefined,
  pickupLocation: undefined,
  dropoffLocation: undefined,
  start: undefined,
  startCity: undefined,
  startAddress: undefined,
  startLatitude: undefined,
  startLongitude: undefined,
  end: undefined,
  endCity: undefined,
  endAddress: undefined,
  endLatitude: undefined,
  endLongitude: undefined,
  orderAmount: undefined,
  serviceDuration: undefined,
  serviceDistance: undefined,
  fromId: undefined,
  payId: undefined,
  mobile: undefined,
  appointmentTime: undefined,
  statusText: undefined,
  remark: undefined,
  driverId: undefined,
})
const formRules = reactive({
  orderNo: [{ required: true, message: '订单号不能为空', trigger: 'blur' }],
  userId: [{ required: true, message: '乘客ID不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await OrderApi.getOrder(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as Order
    if (formType.value === 'create') {
      await OrderApi.createOrder(data)
      message.success(t('common.createSuccess'))
    } else {
      await OrderApi.updateOrder(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    orderId: undefined,
    orderNo: undefined,
    userId: undefined,
    city: undefined,
    vehicleClass: undefined,
    orderStatus: undefined,
    pickupLocation: undefined,
    dropoffLocation: undefined,
    start: undefined,
    startCity: undefined,
    startAddress: undefined,
    startLatitude: undefined,
    startLongitude: undefined,
    end: undefined,
    endCity: undefined,
    endAddress: undefined,
    endLatitude: undefined,
    endLongitude: undefined,
    orderAmount: undefined,
    serviceDuration: undefined,
    serviceDistance: undefined,
    fromId: undefined,
    payId: undefined,
    mobile: undefined,
    appointmentTime: undefined,
    statusText: undefined,
    remark: undefined,
    driverId: undefined,
  }
  formRef.value?.resetFields()
}
</script>